package com.lxk.concurrency.example.count;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import com.lxk.concurrency.annoations.NotThreadSafe;

/**
 * @Description volatile 不具有原子性，所以不适合计数场景，适合做状态标记量，即 boolean 变量，如：可用于标记线程初始化是否完成
 *		
 *		适合使用的条件：
 *
 *			1、对变量的写操作不依赖于当前值
 *
 *			2、该变量没有包含在具有其他变量的不变式中
 *
 * @author 堆堆堆
 * @date 2018年5月25日 上午11:32:54
 */
@NotThreadSafe
public class CountExample4 {

	// 请求总数
	public static int clientTotal = 5000;

	// 同时并发执行的线程数
	public static int threadTotal = 200;

	public static volatile int count = 0;

	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(threadTotal);

		final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

		for (int i = 0; i < clientTotal; i++) {

			executorService.execute(() -> {
				try {

					semaphore.acquire();
					add();
					semaphore.release();

				} catch (Exception e) {
					System.out.println(e);
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		executorService.shutdown();

		System.out.println("count:" + count);
	}

	private static void add() {
		count++;
		
		// 1、count 读出
		// 2、+1
		// 3、count 写入
	}
}
